import commands
import shutil
import os


def chunkJSFile(infile, outdir):
	inf = open(infile, 'r')
	contents = inf.read()
	contents = contents.split("Script::Compile")[1:]

	counter = 0
	evalcounter = 0
	
	# Remove the directory if exists, create after remove.
	if os.path.exists(outdir):
		if os.path.isfile(outdir):
			print 'The out dir is conflict with other filename'
			return
		shutil.rmtree(outdir)
	os.makedirs(outdir)

	for content in contents:
		if len(content) > 6 and content[0:6] == "Eval::":
			content = content[6:]
			# content[0] is the context type, content[1] is the eval output.
			content = content.split("Context::\n")
			if len(content) != 2:
				print "The javascript contains literal Context::\n{0}".format(content)
				continue
			outfilename = outdir + '/' + content[0] + 'Eval'
			content = content[1]
			if content == '\n' or content == '':
				continue
			outfile = open(outfilename + str(evalcounter), 'w')
			evalcounter += 1
		else:
			content = content[1:]
			outfile = open(outdir + '/' + str(counter), 'w')
			counter += 1
		outfile.write(content)
		outfile.close()

	
def chunkJSDir(indir, outdir):
	infiles = commands.getoutput("ls " + indir + "/*.js").split('\n')
	for infile in infiles:
		tempoutdir = infile
		tempoutdir = outdir + tempoutdir.split('/')[-1].split('.')[0] + '/'
		chunkJSFile(infile, tempoutdir)


if __name__=="__main__":
	# chunkJSFile("../../data/TempData/JSFiles/google.js", "../../data/TempData/JSFiles/google/")
	chunkJSDir("../../data/TempData/JSFiles/", "../../data/TempData/JSFiles/")
